/*
 * Main.java
 *
 * Created on 27 de diciembre de 2008, 2:27
 */

package not.visual;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.Dimension;

import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Point;


import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Vector;



import java.util.logging.Level;
import java.util.logging.Logger;
import not.beans.Nota;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

/**
 *Esta es la clase principal del proyecto de Notas que estoy realizando
 * @version 1.O
 * @author  Guille
**/
//TODO: Si Main heredado de JDialog no funciona satisfactoriamente, heredar de JFrame
//TODO: System Tray
public class Main extends javax.swing.JDialog {
   
    /*
     * Toolkit para medir la dimension de la pantalla
     */
    private SystemTray st;
private Toolkit t = Toolkit.getDefaultToolkit();
private String OsName = System.getProperty("os.name");
 Locale l = Locale.getDefault();
  ResourceBundle rb = ResourceBundle.getBundle("org.i18n.messages",l);
/*
 * La dimension de la pantalla
 */
private Dimension d = t.getScreenSize();
 
/*
 * Grosor del Frame
 */
private final int FRAME_WIDTH = (int) d.getWidth()/7;
/*
 * Vector que contiene las notas
 */
private Vector<not.beans.Nota> notitas;
private not.save.Saver s;
private javax.swing.Timer timer;
private int ind = 0;         
private javax.swing.border.EmptyBorder eb = (EmptyBorder) javax.swing.BorderFactory.createEmptyBorder();

/**
 * Constructor, aqui se inicializan los componentes
 */
   private void escribirTexto(String textoAEscribir,Nota n) {
        if(textoAEscribir.charAt(ind)!=n.getTexto().length()-1){
            
            n.setTexto(n.getTexto()+String.valueOf(textoAEscribir.charAt(ind)));
            ind++;
        }
            }
   private void cargarDatos()
   {
     try {
            not.save.Loader l = new not.save.Loader();
             notitas = l.getNotas();
   
            
           for(int i=0;i<notitas.size();i++)
            {
               
      
             
           this.crearBotonDeNota(notitas.get(i));
           
        notitas.get(i).setBackground(Color.WHITE);
         notas.add(notitas.get(i));
              

            }
               
          

 
                
        } catch (Exception ex) {
           ex.printStackTrace();
           notitas = new Vector<not.beans.Nota>();
        }
   }
    public Main() {
      
        try
        {
            
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
      
     
 
        initComponents();


       posicionarDerecha();

    cargarDatos();
     
       if(SystemTray.isSupported()==true)
       {
           
           st = SystemTray.getSystemTray();
           ImageIcon icon = new ImageIcon(getClass().getResource("Nota.gif"));
           
         TrayIcon ti = new TrayIcon(icon.getImage(),"NoteSite");
        ti.setImageAutoSize(true);
        PopupMenu pm = new PopupMenu();
        MenuItem salir = new MenuItem(rb.getString("note.taskbar.options.close"));
        MenuItem ver = new MenuItem(rb.getString("note.taskbar.options.show"));
        salir.addActionListener(new ActionListener()
        {

                public void actionPerformed(ActionEvent e) {
                 int valor = JOptionPane.showConfirmDialog(null,rb.getString("note.closedialog.confirm"),rb.getString("note.closedialog.form.title"),JOptionPane.YES_NO_OPTION);
                 
                  {
                      if(valor==JOptionPane.YES_OPTION)
                      {
                          System.exit(0);
                      }
                  }
                         
                }
            
        });
        ver.addActionListener(new ActionListener()
        {

                public void actionPerformed(ActionEvent e) {
                  accionesIcono();
                }
            
        });
        ti.addActionListener(new ActionListener()
                
        {

                public void actionPerformed(ActionEvent e) {
                   
                  accionesIcono();
                }

              
            
        });
        pm.add(ver);
        
        pm.add(salir);
        ti.setPopupMenu(pm);
            try {
                st.add(ti);
                
            } catch (AWTException ex) {
               ex.printStackTrace();
            }

       }
    }
  private void accionesIcono() {
                   this.setVisible(true);
                }
    /**Este metodo inicializa los componentes.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        barraDeNotas = new javax.swing.JScrollPane();
        if(!this.OsName.equals("Windows XP"))
{
    System.out.println(OsName);
this.add(javax.swing.Box.createVerticalStrut(30));
}
        notas = new javax.swing.JPanel();
        agregador = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        botonDeSalida = new javax.swing.JButton();
        botonParaAgregar = new javax.swing.JButton();
        botonParaLimpiar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setBackground(new java.awt.Color(0, 102, 255));
        setResizable(false);
        setUndecorated(true);
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS));

        barraDeNotas.setPreferredSize(new Dimension(this.FRAME_WIDTH,400));
        barraDeNotas.setRequestFocusEnabled(false);

        notas.setBackground(new java.awt.Color(255, 255, 255));
        notas.setLayout(new javax.swing.BoxLayout(notas, javax.swing.BoxLayout.Y_AXIS));
        barraDeNotas.setViewportView(notas);

        getContentPane().add(barraDeNotas);

        agregador.setMaximumSize(new Dimension(this.FRAME_WIDTH,200));
        agregador.setPreferredSize(new java.awt.Dimension(388, 200));

        jLabel1.setText(rb.getString("note.title"));

        jTextField1.setFont(new java.awt.Font("Tahoma", 1, 14));
        jTextField1.setForeground(new java.awt.Color(0, 102, 204));

        jLabel2.setText(rb.getString("note.text"));

        botonDeSalida.setText(rb.getString("note.options.exit"));
        botonDeSalida.setPreferredSize(new java.awt.Dimension(59, 35));
        botonDeSalida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonDeSalidaActionPerformed(evt);
            }
        });

        botonParaAgregar.setText(rb.getString("note.options.add"));
        botonParaAgregar.setPreferredSize(new java.awt.Dimension(60, 19));
        botonParaAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonParaAgregarActionPerformed(evt);
            }
        });

        botonParaLimpiar.setText(rb.getString("note.options.clean"));
        botonParaLimpiar.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
        botonParaLimpiar.setMaximumSize(new java.awt.Dimension(79, 25));
        botonParaLimpiar.setPreferredSize(new java.awt.Dimension(79, 25));
        botonParaLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonParaLimpiarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout agregadorLayout = new javax.swing.GroupLayout(agregador);
        agregador.setLayout(agregadorLayout);
        agregadorLayout.setHorizontalGroup(
            agregadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(agregadorLayout.createSequentialGroup()
                .addGroup(agregadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(agregadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(agregadorLayout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jTextField2))
                        .addGroup(agregadorLayout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(agregadorLayout.createSequentialGroup()
                            .addComponent(botonParaAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(botonParaLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(botonDeSalida, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(182, Short.MAX_VALUE))
        );
        agregadorLayout.setVerticalGroup(
            agregadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(agregadorLayout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(agregadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(agregadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(agregadorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonParaAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botonParaLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botonDeSalida, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(398, 398, 398))
        );

        getContentPane().add(agregador);

        pack();
    }// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Acciones de Botones">
    /**
     *En este metodo, se cierra el programa
     * @param evt
     */
private void botonDeSalidaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonDeSalidaActionPerformed

 System.exit(0);
}//GEN-LAST:event_botonDeSalidaActionPerformed
/**
 * Este metodo agrega las notas al panel de notas.
 * @param evt
 */
private void botonParaAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonParaAgregarActionPerformed

    Nota laNota = new Nota(jTextField1.getText(),jTextField2.getText());
                   this.crearBotonDeNota(laNota);
                notas.add(laNota);
             
                      notas.updateUI();
             
                notitas.add(laNota);
               s = new not.save.Saver(notitas);
                s.guardarDatos();
    

     posicionarDerecha();
     limpiar();
 
    
}//GEN-LAST:event_botonParaAgregarActionPerformed
//</editor-fold>


private void crearBotonDeNota(not.beans.Nota nb)
{
nb.setToolTipText("<html>Haga click para modificar o eliminar la nota <BR> <B>" +
        "Haga clic en este comentario para ocultarlo");
           nb.setBorder(eb);

       accionesDeNota(nb);
          
            nb.setMaximumSize(new Dimension(10000,40));
      
      
              
}

private void accionesDeNota(final not.beans.Nota nb)
{

    
    nb.addMouseListener(new MouseAdapter()
    {

            public void mouseClicked(MouseEvent e) {
    
 not.visual.Editar edit = new not.visual.Editar(null,true, nb); 
 edit.setVisible(true);
 if(edit.accion==edit.MODIFICADO)
 {
    nb.setTitulo(edit.tituloFinal);
    nb.setTexto(edit.textoFinal);
     s = new not.save.Saver(notitas);
                s.guardarDatos();
                
 }
 else if(edit.accion==edit.BORRADO)
 {
    notas.remove(nb);
    notitas.remove(nb);
      s = new not.save.Saver(notitas);
                s.guardarDatos();
    notas.updateUI();
 }
 nb.setBackground(Color.WHITE);
            }

            public void mouseEntered(MouseEvent e) {
               nb.setBackground(new Color(242,229,188));
            }

            public void mouseExited(MouseEvent e) {
               nb.setBackground(Color.WHITE);
            }
        
    });
}
     

/*
 * Este metodo llama al metodo limpiar
 */
private void botonParaLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonParaLimpiarActionPerformed

    limpiar();
}//GEN-LAST:event_botonParaLimpiarActionPerformed
/*
 * Este metodo limpia los dos cuadros de texto.
 */
    private void limpiar() {
      jTextField1.setText("");
      jTextField2.setText("");
      jTextField1.requestFocus();
    }
    /*
     * Este metodo hace los calculos de tamaño y posicion para que el Frame
     * estee a la derecha de la pantalla.
     */
private void posicionarDerecha()
{
     this.setSize((int)(d.getWidth()/7),(int)(d.getHeight()));
    
        double g = d.getWidth()/1.16575;
      this.setLocation((int)g/(int)(1),0);

      
       Point posi = this.getLocation();
       
 
   
}
    /*
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
                
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel agregador;
    private javax.swing.JScrollPane barraDeNotas;
    private javax.swing.JButton botonDeSalida;
    private javax.swing.JButton botonParaAgregar;
    private javax.swing.JButton botonParaLimpiar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JPanel notas;
    // End of variables declaration//GEN-END:variables

}
